import UIKit
import SDWebImage

public class TF_PopupPutView: UIView {

   @objc public let countdown = UIButton()

    @objc public var mNavigationbarHeight:CGFloat = 0

    var array = NSMutableArray()
    let imageManage = SDWebImageManager.shared
    let view = UIView()
    let imageView = UIImageView()
    let close = UIButton()
    var timer:Timer? = nil
    open var duration:NSInteger = 0
    //保存图片
    let saveBtn = UIButton()
    open var saved:Bool = false
    var url:NSString = ""

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.isHidden = true
    
        self.addSubview(self.view)
        self.view.backgroundColor = UIColor.clear

        self.backgroundColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.6)
        self.imageView.clipsToBounds = true

        let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(urlClick))
        self.imageView.isUserInteractionEnabled = true
        self.imageView.addGestureRecognizer(tapGesture)
        self.view.addSubview(self.imageView)
     
        //TODO:倒计时
        self.countdown.backgroundColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.5)
        self.countdown.layer.cornerRadius = 4
        self.countdown.setTitleColor(UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1), for: .normal)
        self.countdown.titleLabel?.font = UIFont.init(name: "PingFang SC" , size: 13)
        self.view.addSubview(self.countdown)
        
        //TODO:关闭
        self.close.layer.masksToBounds = true
        self.close.setImage(UIImage.init(named: "HTLive.bundle/daka_close"), for: .normal)
        self.close.addTarget(self, action: #selector(closeClick), for: .touchUpInside)
        self.view.addSubview(self.close)

        self.saveBtn.setTitle("保存图片", for: .normal)
         self.saveBtn.backgroundColor = UIColor.white
        self.saveBtn.setTitleColor(UIColor(red: 27/255.0, green: 28/255.0, blue: 29/255.0, alpha: 1), for: .normal)
        self.saveBtn.addTarget(self, action: #selector(saveBtnClick), for: .touchUpInside)
        self.saveBtn.layer.cornerRadius = 3.5
        self.view.addSubview(self.saveBtn)
    }
    
    @objc func saveBtnClick()
    {
        /**
         第三个参数:添加回调的方法
         */
        
        if (self.saved == false) {
            UIImageWriteToSavedPhotosAlbum(self.imageView.image!, self, #selector(saveComplete), nil)
        } else {
            self.showSuccess(msg: "保存图片成功")
        }
    }
    @objc func saveComplete(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        if error != nil {
   
            self.TF_toast("保存图片失败,请打开相册权限")
    
        } else {
            self.saved = true
            
            self.TF_toast("保存图片成功")
        
        }
    }
    
    @objc func closeClick()
    {
        self.duration = 1
        self.timerAction()
    }
    
    
    func timerAction111()
    {
        
        self.duration = self.duration - 1;
   
        if ( self.duration > 0 ) {
            self.countdown.setTitle(NSString.init(format: "%lis后关闭", self.duration) as String, for: .normal)
      
        }
        
        if ( self.duration == 0 ) {
            if((self.timer) != nil)
            {
                self.timer!.invalidate()
                self.timer = nil
            }
            
            if ( self.array.count > 0 )
            {
               
                let result = self.array.firstObject as! TFPopupPut
                self.addPopupPut(result: result)
                self.array.removeObject(at: 0)
          

            }else{

                self.isHidden = true

            }
            }
   
      
    }
    @objc func timerAction()
    {
        
        if Thread.isMainThread {
            //code
            self.timerAction111()
        } else {
            DispatchQueue.main.async {
                self.timerAction111()
            }
        }
   
        }
  @objc public func addPopupPut(result:TFPopupPut)
    {

        let img1:NSString = result.img1 as NSString
        let url = img1.length>0 ? img1 as String : result.img;
        self.url = result.url as NSString;
        if (self.timer == nil) {
            self.isHidden = false
            if (self.countdown.isHidden == false) {
          
                self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
                RunLoop.main.add(self.timer! , forMode: RunLoop.Mode.default)

            }

             self.duration = result.duration;
            
            self.countdown.setTitle(NSString.init(format: "%lis后关闭", result.duration) as String, for: .normal)
           
     
            self.imageManage.loadImage(with: URL.init(string: url), options: SDWebImageOptions.retryFailed) { receivedSize, expectedSize, targetURL in

            } completed: {[weak self] image, data, error, cacheType, finished, imageURL in
                guard let `self` = self else {
                    return
                }

                DispatchQueue.main.async {


                    if (image != nil)  {
                    
                        self.imageView.backgroundColor = UIColor.red
                        self.imageView.image = image
                        
               

                        var imageViewWidth:CGFloat  = 0
                        var imageViewHeight:CGFloat = 0
                        var imageViewX:CGFloat = 0
                        var imageViewY:CGFloat = 0
                            
                        var viewY:CGFloat =  0;
                            if (self.frame.size.height > self.frame.size.width) {
                                imageViewY = 100;
                                viewY =  100;
                                if (self.mNavigationbarHeight > 0 ) {
                                    viewY = 100 + self.mNavigationbarHeight
                                }
                            } else {
                                viewY =  65;
                                imageViewY = 45;
                            }
                           
                        var viewHeight:CGFloat = self.view.frame.size.height - viewY - imageViewY
                        if (image!.size.width >= image!.size.height) {
                                viewHeight = self.view.frame.size.height
                                imageViewWidth = self.view.frame.size.width-40
                                imageViewX = 20;
                               let proportion:CGFloat = image!.size.width/imageViewWidth
                                
                                imageViewHeight = image!.size.height/proportion
                                 
                                imageViewY =  (viewHeight - imageViewHeight )/2
                            }else{
                                imageViewHeight = viewHeight;
                                
                                let proportion:CGFloat = image!.size.height / imageViewHeight
                                
                                imageViewWidth = image!.size.width / proportion
                                
                                imageViewX =  (self.view.frame.size.width - imageViewWidth)/2;
                            }

                        self.imageView.frame = CGRect(x: imageViewX, y: imageViewY, width: imageViewWidth, height: imageViewHeight)
                     
                        self.imageView.contentMode = .scaleAspectFit;
                          
                        self.imageView.layer.cornerRadius = 10
                            
                            //倒计时
                        self.countdown.frame = CGRect(x: self.imageView.frame.maxX-30-10-85, y: self.imageView.frame.origin.y - 30 - 5, width: 85, height: 30)
                            
                        self.close.frame = CGRect(x: self.countdown.frame.maxX+10, y: imageViewY-30-5, width: 30, height: 30)
                        
                    
                        
                            if (self.frame.size.height > self.frame.size.width) {
                                self.saveBtn.frame = CGRect(x: (self.view.frame.size.width - 100)/2, y: self.imageView.frame.maxY+20, width: 100, height: 40)
                                
                               
                            } else {
                                self.saveBtn.frame = CGRect(x: (self.view.frame.size.width - 100)/2, y: self.imageView.frame.maxY+10, width: 100, height: 40)
                              
                            }
                           
                        self.saveBtn.isHidden = !result.saveButton
                           
                        
                    }

                }
            }
            
           
        }else{
            self.array.add(result)
           
        }
        

    }
    
    @objc func urlClick()
    {
        if (self.url.length > 4) {
            TalkfunSharedTools.openUrl(str: self.url)
          
        }
      
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func showSuccess(msg:NSString)
    {
      
        self.TF_toast(msg as String)
        
    }
    public override func layoutSubviews() {
        super.layoutSubviews()
        self.view.frame  = self.bounds;
    }
}
